package xiaolong.zhou.spring_demo.Service.achieve;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import groovy.util.logging.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import xiaolong.zhou.spring_demo.Mapper.UserMapper;
import xiaolong.zhou.spring_demo.Pojo.Login;
import xiaolong.zhou.spring_demo.Pojo.User;
import xiaolong.zhou.spring_demo.Service.UserLogin;
import xiaolong.zhou.spring_demo.Utils.Result;
import xiaolong.zhou.spring_demo.Utils.Token;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class UserLoginAchieve implements UserLogin {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 用户登录实现
     * @param login
     * @return
     */
    @Override
    public Result login(Login login){
        if(redisTemplate.opsForValue().get(login.getSessionId()) == null){
            return Result.error("图形验证码过期");
        }

        if(!Objects.equals(redisTemplate.opsForValue().get(login.getSessionId()), login.getCaptcha().toLowerCase())){
            return Result.error("图形验证码错误");
        }
        String passwordMd5 = DigestUtils.md5DigestAsHex(login.getPassword().getBytes());
        System.out.println(passwordMd5);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",login.getAccount());
        queryWrapper.eq("password",passwordMd5);
        queryWrapper.eq("delete_time","");
        User userInfo = userMapper.selectOne(queryWrapper);
        if(userInfo==null){
            queryWrapper.clear();
            queryWrapper.eq("email",login.getAccount());
            queryWrapper.eq("password",passwordMd5);
            queryWrapper.eq("delete_time","");
            userInfo = userMapper.selectOne(queryWrapper);
        }
        if(userInfo == null){
            return Result.error("用户名或密码错误");
        }

        Map<String ,Object> claims = new HashMap<>();
        claims.put("id",userInfo.getId());
        claims.put("phone",userInfo.getPhone());
        claims.put("email",userInfo.getEmail());
        claims.put("avatar",userInfo.getAvatar());
        claims.put("price",userInfo.getPrice());
        claims.put("token", Token.GenerateToken(claims));
        return Result.success(claims);
    }
}
